// 路由鉴权,路由跳转前判断用户是否拥有该路由权限
import router from "@/router";
import { useStore } from "@/store/index";
import ACCESS_ENUM from "@/access/accessEnum";
import checkAccess from "@/access/checkAccess";

/**
 * 路由跳转前，路由处理逻辑
 */
router.beforeEach(async (to, from, next) => {
  console.log("前置路由校验！！！");
  const store = useStore();
  const loginUser = store.loginUser;

  // 如果之前没有登陆，自动登录
  if (loginUser.userRole == null) {
    await store.getLoginUser();
  }
  // 获取跳转的菜单权限
  const needAccess = to.meta?.assess ?? ACCESS_ENUM.NOT_LOGIN;
  // 要跳转的页面必须要登录
  if (needAccess !== ACCESS_ENUM.NOT_LOGIN) {
    // 如果没有登录，直接继续执行
    if (loginUser.userRole == null) {
      next(`/user/login?redirect=${to.fullPath}`);
      return;
    }
    // 如果已经登录了，但是权限不足，那么跳转到无权页面
    if (!checkAccess(loginUser, needAccess as string)) {
      next("/noAuth");
      return;
    }
  }
  next();
});
